﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace MicroDal.Context
{
    internal class ThreadSessionStorage : ISessionStorage
    {
        [ThreadStatic]
        private static DataSession _session;

        public DataSession GetCurrent()
        {
            if (_session == null || _session.IsDisposed)
            {
                _session = new DataSession(GetMicroDalConnectionName());
            }
            return _session;
        }
        public DataSession Get(string name)
        {
            throw new NotImplementedException();
        }

        ~ThreadSessionStorage()
        {
            if (_session != null)
            {
                _session.Dispose();
            }
        }

        private static string GetMicroDalConnectionName()
        {
            var name = ConfigurationManager.AppSettings["MicroDalConnectionName"] ?? ConfigurationManager.ConnectionStrings[0].Name;
            if (string.IsNullOrEmpty(name))
                throw new ConfigurationErrorsException("There should be at least one database connection configured");

            return name;
        }
    }
}
